import { useState, useEffect } from 'react';
import Select, { OnChangeValue, StylesConfig } from 'react-select';
import { FileType } from '../../../main/const';
import { Button } from 'antd';
import { MinusCountButton } from '../../components/MinusCountButton';

const colourStyles: StylesConfig = {
  option: (styles, { isFocused }) => {
    return {
      ...styles,
      backgroundColor: isFocused ? 'gray' : 'white',
      color: 'black',
    };
  },
};

const getSameColumn = (column1: string[], column2: string[]) => {
  const res: string[] = [];
  Object.values(column1).forEach((c1) => {
    Object.values(column2).forEach((c2) => {
      if (c1 === c2) {
        res.push(c1);
      }
    });
  });
  return res;
};

const getExportColumn = (column1: string[], column2: string[]): string[] => {
  const res = new Set<string>();
  Object.values(column1).forEach((c1) => {
    res.add(c1);
  });
  Object.values(column2).forEach((c2) => {
    res.add(c2);
  });
  return [...res];
};

function HorizontalMergePage() {
  const [importedFiles, setImportedFiles] = useState([] as any);
  const [exportFile, setExportFile] = useState('');
  const [fileColumn, setFileColumn] = useState([] as any);
  const [sameColumns, setSameColumns] = useState([] as string[]);
  const [exportColumns, setExportColumns] = useState([] as string[]);
  const [selectedSameColOption, setSelectedSameColOption] = useState(
    [] as string[]
  );
  const [selectedExportColOption, setSelectedExportColOption] = useState(
    [] as string[]
  );
  const [sameColumnOptions, setSameColumnOptions] = useState(
    [] as { value: string; label: string }[]
  );
  const [exportColumnOptions, setExportColumnOptions] = useState(
    [] as { value: string; label: string }[]
  );
  useEffect(() => {
    const fn = async () => {
      if (importedFiles.length === 2) {
        const column0 = await window.electronAPI.ipcRenderer.getColumn(
          importedFiles[0]
        );
        const column1 = await window.electronAPI.ipcRenderer.getColumn(
          importedFiles[1]
        );
        setFileColumn([column0, column1]);
      } else {
        setFileColumn([]);
      }
    };
    fn();
  }, [importedFiles]);
  useEffect(() => {
    if (fileColumn.length === 2) {
      setSameColumns(getSameColumn(fileColumn[0], fileColumn[1]));
      setExportColumns(getExportColumn(fileColumn[0], fileColumn[1]));
    }
  }, [fileColumn]);
  useEffect(() => {
    if (sameColumns.length >= 2) {
      const ops: { value: string; label: string }[] = [];
      Object.values(sameColumns).forEach((v) => {
        ops.push({ value: v, label: v });
      });
      setSameColumnOptions(ops);
    }
  }, [sameColumns]);
  useEffect(() => {
    if (exportColumns.length >= 2) {
      const ops: { value: string; label: string }[] = [];
      Object.values(exportColumns).forEach((v) => {
        ops.push({ value: v, label: v });
      });
      setExportColumnOptions(ops);
    }
  }, [exportColumns]);
  const clickImport = () => {
    window.electronAPI.ipcRenderer
      .chooseFiles(FileType.XLSX)
      .then((filePaths) => {
        if (filePaths) {
          if (filePaths.length === 2) {
            setImportedFiles(filePaths);
          } else {
            window.electronAPI.ipcRenderer.showError(
              '错误',
              '需要选择两个文件'
            );
          }
        } else {
          setImportedFiles([]);
          window.electronAPI.ipcRenderer.showError('错误', '需要选择两个文件');
        }
      });
  };
  const clickExport = async () => {
    window.electronAPI.ipcRenderer.chooseDir().then((res) => {
      setExportFile(`${res}/export.xlsx`);
    });
  };
  const clickMerge = async () => {
    if (importedFiles.length !== 2) {
      window.electronAPI.ipcRenderer.showError('错误', '需要选择两个文件');
      return;
    }
    if (exportFile === '') {
      window.electronAPI.ipcRenderer.showError('错误', '需要选择导出路径');
      return;
    }
    if (selectedSameColOption.length !== 2) {
      window.electronAPI.ipcRenderer.showError('错误', '必须选择两列');
      return;
    }
    if (selectedExportColOption.length <= 0) {
      window.electronAPI.ipcRenderer.showError('错误', '至少选择一个导出列');
    }
    window.electronAPI.ipcRenderer
      .doMerge(
        importedFiles[0],
        importedFiles[1],
        exportFile,
        selectedSameColOption,
        selectedExportColOption
      )
      .then((res) => {
        window.electronAPI.ipcRenderer.showMessage('提示', '导出成功');
        return '';
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const onSameColChange = (
    newValue: OnChangeValue<any, any>,
    actionMeta: any
  ) => {
    const res: string[] = [];
    Object.values(newValue as { value: string; label: string }[]).forEach(
      (v) => {
        res.push(v.value);
      }
    );
    setSelectedSameColOption(res);
  };
  const onExportColChange = (
    newValue: OnChangeValue<any, any>,
    actionMeta: any
  ) => {
    const res: string[] = [];
    Object.values(newValue as { value: string; label: string }[]).forEach(
      (v) => {
        res.push(v.value);
      }
    );
    setSelectedExportColOption(res);
  };
  return (
    <div>
      <div>
        <h1>双列合并</h1>
        <Button onClick={clickImport}>1. 选择两个数据文件</Button>
        <div>文件1: {importedFiles[0]}</div>
        <div>文件2: {importedFiles[1]}</div>
      </div>
      <div>
        <Button onClick={clickExport}>2. 设置导出文件夹</Button>
        <div>导出路径: {exportFile}</div>
      </div>
      <div>
        <div>3. 选择双列</div>
        <Select
          defaultValue={selectedSameColOption}
          options={sameColumnOptions}
          isMulti
          styles={colourStyles}
          onChange={onSameColChange}
        />
      </div>
      <div>
        <div>4. 选择需要导出的列</div>
        <Select
          defaultValue={selectedSameColOption}
          options={exportColumnOptions}
          isMulti
          styles={colourStyles}
          onChange={onExportColChange}
        />
      </div>
      <div>
        <MinusCountButton
          type="primary"
          onCustomClick={clickMerge}
          style={{ marginTop: 10 }}
        >
          5. 开始合并
        </MinusCountButton>
      </div>
    </div>
  );
}
export default HorizontalMergePage;
